/*
 * Created on Oct 20, 2005
 *
 */
package org.mushroomdb.security.jaas;

import java.io.IOException;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;

/**
 * @author Matu
 *
 */
public class UserNamePasswordCallbackHandler implements CallbackHandler {
	private String userName;
	private char[] password;

	/**
	 * Default constructor.
	 */
	public UserNamePasswordCallbackHandler() {		
	}

	/**
	 * Creates a handler for the desired username and password.
	 * @param name
	 * @param password
	 */
	public UserNamePasswordCallbackHandler(String userName, char[] password) {
		this.userName = userName;
		this.password = password;
	}
	
	/**
	 * @see javax.security.auth.callback.CallbackHandler#handle(javax.security.auth.callback.Callback[])
	 */
	public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
		for (int i = 0; i < callbacks.length; i++) {
			if (callbacks[i] instanceof NameCallback) {
				((NameCallback) callbacks[i]).setName(this.userName);
			} else if (callbacks[i] instanceof PasswordCallback) {
				((PasswordCallback) callbacks[i]).setPassword(this.password);
			} else {
				throw new UnsupportedCallbackException(callbacks[i]);
			}
		}
	}

}
